class Compiler {
  constructor (vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }

  //* 编译模板，处理文本节点和元素节点
  compile (el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach((node) => {
      if (this.isTextNode(node)) {
        // 处理文本节点
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        // 处理元素节点
        this.compileElement(node)
      }

      // 判断node是否还有子节点，如果有就继续递归调用compile
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }

  //* 编译元素节点，处理指令
  compileElement (node) {
    // console.log(node.attributes)
    // 遍历所有属性节点
    Array.from(node.attributes).forEach((attr) => {
      // 判断是否是指令
      let attrName = attr.name
      if (this.isDirective(attrName)) {
        // v-text --> text 去掉v-前缀
        attrName = attrName.substr(2)
        // 匹配带有冒号的指令，比如v-on:click
        let pattern = /(\w+):?(\w*)/.exec(attrName)
        let directiveName = pattern[1]
        let directiveEvent = pattern[2]
        // 找到对应的data成员名，比如v-text="msg"，msg就是data中的成员
        let key = attr.value

        this.update(node, key, directiveName, directiveEvent)
      }
    })
  }

  //* SECTION 指令处理函数

  update (node, key, attrName, event) {
    // 通过拼接函数名找到处理函数，避免if语句
    let updateFn = this[attrName + 'Updater']
    // 注意调用时this的指向
    updateFn && updateFn.call(this, node, key, this.vm[key], event)
  }
  // v-text
  textUpdater (node, key, value) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  // v-model
  modelUpdater (node, key, value) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    // 双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }
  // v-html
  htmlUpdater (node, key, value) {
    node.innerHTML = value
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }
  // v-on
  onUpdater (node, key, value, event) {
    if (event && value) {
      node.addEventListener(event, value)
    }
  }

  //* !SECTION

  //* 编译文本节点，处理插值表达式
  compileText (node) {
    // console.dir(node)
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    let result = reg.exec(value)
    if (result) {
      let key = result[1].trim()
      node.textContent = value.replace(reg, this.vm[key])

      //* 创建watcher
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }
  }

  //* 判断元素属性是否为指令
  isDirective (attrName) {
    return attrName.startsWith('v-')
  }

  //* 判断节点是否为文本节点
  isTextNode (node) {
    return node.nodeType === Node.TEXT_NODE // 3
  }

  //* 判断节点是否是元素节点
  isElementNode (node) {
    return node.nodeType === Node.ELEMENT_NODE // 1
  }
}
